package sg.edu.nus.iss.jass.gui;

import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import sg.edu.nus.iss.jass.constant.ActionBtnContants;
import sg.edu.nus.iss.jass.constant.ErrorConstants;
import sg.edu.nus.iss.jass.controller.JobAdvertisementController;
import sg.edu.nus.iss.jass.dto.JobAdvert;
import sg.edu.nus.iss.jass.dto.JobResponse;
import sg.edu.nus.iss.jass.dto.JobSeeker;
import sg.edu.nus.iss.jass.dto.Resume;
import sg.edu.nus.iss.jass.dto.Skill;
import sg.edu.nus.iss.jass.exception.ValidationException;
import sg.edu.nus.iss.jass.gui.component.TitleLabel;
import sg.edu.nus.iss.jass.gui.component.ValidateJTextField;
import sg.edu.nus.iss.jass.util.Util;
import sg.edu.nus.iss.jass.validation.ValidationRule;


/**
 * <h5>JobApplicationFormPanel to load the form for Apply Job  </h5>
 * @author Kafoor Sammil
 * 
 */
public class JobApplicationFormPanel extends FormPanel  {
	
	
	private JLabel applDetailLbl;
	private JLabel nameLbl;
	private JLabel telNoLbl;
	private JLabel emailLbl;
	private JLabel userIdLbl;
	private JLabel addressLbl;

	
	
	private JLabel jobDetailLbl;
	private JLabel resumeDetailLbl;
	
	
	private JLabel jobTitleLbl; 
	private JLabel jobPositionLbl;
	private JLabel jobDescriptionLbl;
	private JLabel locationCountryLbl;
	private JLabel companyLbl;
	private JLabel resumeLbl;
	 
	private ValidateJTextField jobTitleTxtField; 
	private ValidateJTextField positionTxtField;
	private ValidateJTextField jobDescriptionTxtField;
	private ValidateJTextField locationCountryTxtField; 
	private ValidateJTextField companyTxtField;
	
	
	private ValidateJTextField nameTxtField;
	private ValidateJTextField telNoTxtField;
	private ValidateJTextField emailTxtField;
	private ValidateJTextField userIdTxtField;
	private ValidateJTextField addressTxtField;;
	
	private JComboBox resumesCbx;
	private JButton previewButton;
	private JLabel currentSalLbl;
	private JLabel expSalLbl;
	private ValidateJTextField currentSalTxtField;
	private ValidateJTextField expSalTxtField;
	
	
	private MainFrame mainframe;
	private JobAdvert jobAdvert = null;
	private JobSeeker jobSeeker = null;
	
	private JPanel skillsPanel;
	List<Skill> skillsList = null;
	int noOfSkills = 0;
	
	float currentSalary = 0;
	 float expectedSalary = 0;
	
	JLabel skillLabel[] = null;
	JComboBox skillLevelCbx[] = null;
	ValidateJTextField  skillExpTxtField[] = null;
	
	JobResponse jobResponse = null;
	
	private int COMPONENT_WIDTH = 150;
	private int COMPONENT_HEIGHT = 25;
	
	private JobAdvertisementController jobAdvertisementController;
	String skillLevels[] = {"Select","Beginner", "Intermediate", "Advanced"};
	
	private List<Skill> responseSkillList = null;
	private List<Resume> resumes = null;
	
	JPanel resumePreviewPanel = null;
	JScrollPane resumePreviewScroller = null;
	
	public JobApplicationFormPanel(MainFrame mainframe, ActionPanel actionPanel,
			HeaderPanel headerPanel, JobAdvert jobAdvert,JobSeeker jobSeeker,List<Resume> resumes) {
		super(mainframe, actionPanel, headerPanel );
		this.mainframe = mainframe;
		this.jobAdvert = jobAdvert;
		this.jobSeeker = jobSeeker;
		this.resumes = resumes;
		if(jobAdvert != null){
			initGUI();
			setInitData();
   		}
        else{
        	clearMsg();
        	showMsg(ErrorConstants.ERROR_NO_DATA, false);        	
        }
	}
	
	
	
	public void setController(JobAdvertisementController jobAdvertisementController){
		this.jobAdvertisementController = jobAdvertisementController;
		
	}	
	
	
	private void initGUI() {
		
		//===========================Applicant Details=======================================
		this.applDetailLbl = new TitleLabel("Applicant Details");
		applDetailLbl.setBounds(10, 10, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.applDetailLbl);
		
		
		this.nameLbl = new JLabel("Name:");
		nameLbl.setBounds(10, 50, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.nameLbl);
		
		nameTxtField = new ValidateJTextField("Name",ValidationRule.NOT_NULL);
		nameTxtField.setBounds(150, 50, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.nameTxtField);
		
		
		this.userIdLbl = new JLabel("User ID:");
		userIdLbl.setBounds(400, 50, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.userIdLbl);
		
		userIdTxtField = new ValidateJTextField("User ID",ValidationRule.NOT_NULL);
		userIdTxtField.setBounds(550, 50, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.userIdTxtField);
		userIdTxtField.setEditable(false);
		
		this.emailLbl = new JLabel("Email:");
		emailLbl.setBounds(10, 90, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.emailLbl);
		
		emailTxtField = new ValidateJTextField("Email",ValidationRule.NOT_NULL,ValidationRule.EMAIL);
		emailTxtField.setBounds(150, 90, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.emailTxtField);
		
		
		this.telNoLbl = new JLabel("Telephone:");
		telNoLbl.setBounds(400, 90, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.telNoLbl);
		
		telNoTxtField = new ValidateJTextField("Telephone",ValidationRule.NUMERIC);
		telNoTxtField.setBounds(550, 90, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.telNoTxtField);
		
		
		this.addressLbl = new JLabel("Address:");
		addressLbl.setBounds(10, 130, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.addressLbl);
		
		addressTxtField = new ValidateJTextField("Address",ValidationRule.NOT_NULL);
		addressTxtField.setBounds(150, 130, COMPONENT_WIDTH * 2, COMPONENT_HEIGHT);
		this.add(this.addressTxtField);
		
		//====Resume Details
		this.resumeDetailLbl = new TitleLabel("Resume Details");
		resumeDetailLbl.setBounds(10, 200, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.resumeDetailLbl);
		
		this.resumeLbl = new JLabel("Select Resume:");
		resumeLbl.setBounds(10, 240, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(resumeLbl);
		
		this.resumesCbx = new JComboBox();
		resumesCbx.setBounds(150, 240, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(resumesCbx);
		
		
		this.previewButton = new JButton("Preview Resume");
		previewButton.setBounds(340, 240, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(previewButton);
		previewButton.addActionListener(this);
		
		
		//===========================Job Details=======================================
		this.jobDetailLbl = new TitleLabel("Job Details");
		jobDetailLbl.setBounds(10, 500, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.jobDetailLbl);
		
		this.jobTitleLbl = new JLabel("Job Title:");
		jobTitleLbl.setBounds(10, 540, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.jobTitleLbl);
		
		jobTitleTxtField = new ValidateJTextField("Job Title",ValidationRule.NOT_NULL);
		jobTitleTxtField.setBounds(150, 540, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		jobTitleTxtField.setEditable(false);
		this.add(this.jobTitleTxtField);
		
				
		
		this.jobPositionLbl = new JLabel("Job Position:");
		jobPositionLbl.setBounds(400, 540, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.jobPositionLbl);
		
		positionTxtField = new ValidateJTextField("Job Position",ValidationRule.NOT_NULL);
		positionTxtField.setBounds(550, 540, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		positionTxtField.setEditable(false);
		this.add(this.positionTxtField);
		
		

		this.companyLbl = new JLabel("Company:");
		companyLbl.setBounds(10, 580, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.companyLbl);
		
		companyTxtField = new ValidateJTextField("Company",ValidationRule.NOT_NULL);
		companyTxtField.setBounds( 150, 580,COMPONENT_WIDTH, COMPONENT_HEIGHT);
		companyTxtField.setEditable(false);
		this.add(this.companyTxtField);
		
		
		this.locationCountryLbl = new JLabel("Location:");
		locationCountryLbl.setBounds(400, 580, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.locationCountryLbl);
		
		locationCountryTxtField = new ValidateJTextField("Location",ValidationRule.NOT_NULL);
		locationCountryTxtField.setBounds(550, 580, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		locationCountryTxtField.setEditable(false);
		this.add(this.locationCountryTxtField);
				
		
		this.jobDescriptionLbl = new JLabel("Job Description:");
		jobDescriptionLbl.setBounds(10, 620, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.jobDescriptionLbl);
		
		jobDescriptionTxtField = new ValidateJTextField("Job Description",ValidationRule.NOT_NULL);
		jobDescriptionTxtField.setBounds(150, 620, COMPONENT_WIDTH * 2, COMPONENT_HEIGHT);
		jobDescriptionTxtField.setEditable(false);
		this.add(this.jobDescriptionTxtField);
		
		//==== Salary Details
		TitleLabel salaryDetailLbl = new TitleLabel("Salary Details");
		salaryDetailLbl.setBounds(10, 850, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(salaryDetailLbl);
	
		
		this.currentSalLbl = new JLabel("Current Salary:");
		this.currentSalLbl.setBounds(10, 890, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.currentSalLbl);
		
		this.currentSalTxtField = new ValidateJTextField("Current Salary",ValidationRule.NUMERIC);
		this.currentSalTxtField.setBounds(150, 890, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.currentSalTxtField);
		
		this.expSalLbl = new JLabel("Expected Salary:");
		this.expSalLbl.setBounds(400, 890, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.expSalLbl);
		
		this.expSalTxtField = new ValidateJTextField("Expected Salary",ValidationRule.NUMERIC);
		this.expSalTxtField.setBounds(550, 890, COMPONENT_WIDTH, COMPONENT_HEIGHT);
		this.add(this.expSalTxtField);
		
		
		
	}
	
private JPanel createResumePreviewPanel(Resume  resume) {
		
		JPanel pane = new JPanel(new GridLayout ());
		pane.setBackground(Color.lightGray);
		pane.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		
		int noOfResumeSkills  = 0;
		
		
		ArrayList<Skill> resumeSkillsList = resume.getSkillDetails();
		System.out.println(" createResumePreviewPanel resumeSkillsList : " + resumeSkillsList.size() );
		
		noOfResumeSkills = resumeSkillsList.size();
		
		JLabel resumeSkillLabel[] = null;
		JLabel resumeskillLevelLabel[] = null;
		JLabel resumeSkillExpLabel[] = null;
		
		c.fill = GridBagConstraints.HORIZONTAL;
		c.weightx = 1.5;	
		c.weighty = 0.5;
		c.insets = new Insets(5, 5, 5, 5);
		c.ipady = 10;
	 
		//Resume Name :
		c.gridx = 0;
		c.gridy = 0;
		pane.add(new JLabel("Resume Name:"), c);
		
		c.gridx = 1;
		c.gridy = 0;
		JTextField resumeNameTxtField = new JTextField(resume.getResumeName());
		resumeNameTxtField.setBackground(Color.lightGray);
		resumeNameTxtField.setEditable(false);
		pane.add(resumeNameTxtField, c);
		
		
		//Resume Desc :
		c.gridx = 0;
		c.gridy = 1;
	   
		pane.add(new JLabel("Resume Description:"), c);
		
		c.gridx = 1;
		c.gridy = 1;
		c.gridwidth = 2;
		JTextField resumeDescTxtField = new JTextField(resume.getResumeDesc());
		resumeDescTxtField.setBackground(Color.lightGray);
		resumeDescTxtField.setEditable(false);
		pane.add(resumeDescTxtField, c);
		
		c.gridwidth = 0;
		c.gridx = 0;
		c.gridy = 2;
		JLabel skillLbl = new JLabel("Skill");
		skillLbl.setFont(new Font("Arial", Font.BOLD, 15));
		pane.add(skillLbl, c);
		
		
		c.gridx = 1;
		c.gridy = 2;
		JLabel skillLevelLbl = new JLabel("Skill Level");
		skillLevelLbl.setFont(new Font("Arial", Font.BOLD, 15));
		pane.add(skillLevelLbl, c);

		c.gridx = 2;
		c.gridy = 2;
		JLabel skillExpLbl = new JLabel("Years Of Experience");
		skillExpLbl.setFont(new Font("Arial", Font.BOLD, 15));
		pane.add(skillExpLbl, c);
        
		
		resumeSkillLabel = new JLabel[noOfResumeSkills];
		resumeskillLevelLabel = new JLabel[noOfResumeSkills];
		resumeSkillExpLabel = new JLabel[noOfResumeSkills];
		
		
		for (int i = 0;i<noOfResumeSkills;i++) {
			
		
			Skill skill = resumeSkillsList.get(i);
			
			resumeSkillLabel[i] = new JLabel (skill.getSkillRef().getName());
			c.gridx = 0;
			c.gridy = i + 3;
			pane.add(resumeSkillLabel[i], c);
			
			
			resumeskillLevelLabel[i] = new JLabel (Util.getSkillLevel(skill.getLvl()));
			c.gridx = 1;
			c.gridy = i + 3;
			pane.add(resumeskillLevelLabel[i], c);
			
			
			resumeSkillExpLabel[i] = new JLabel (""+skill.getYearOfExp());
			c.gridx = 2;
			c.gridy = i + 3;
			pane.add(resumeSkillExpLabel[i], c);
			
		}
		
		return pane;
	}

	
private JPanel createSkillsPanel() {
		
		JPanel pane = new JPanel(new GridLayout ());
		pane.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.weightx = 1.5;
		c.weighty = 0.5;
		c.insets = new Insets(5, 5, 5, 5);
		c.ipady = 10;
	 
		c.gridx = 0;
		c.gridy = 0;
		pane.add(new JLabel("Skill"), c);
		
		c.gridx = 1;
		c.gridy = 0;
		pane.add(new JLabel("Skill Level"), c);

		c.gridx = 2;
		c.gridy = 0;
		pane.add(new JLabel("Years Of Experience"), c);
        
		
		
		skillLabel = new JLabel[noOfSkills];
		int y = 1;
		for (int i = 0;i<noOfSkills;i++) {
			Skill skill = skillsList.get(i);
			skillLabel[i] = new JLabel (skill.getSkillRef().getName());
			c.gridx = 0;
			c.gridy = y++;
			pane.add(skillLabel[i], c);
		}
		
		skillLevelCbx = new JComboBox[noOfSkills];
		y = 1;
		for (int i = 0;i<noOfSkills;i++) {
			skillLevelCbx[i] = new JComboBox (skillLevels);
			c.gridx = 1;
			c.gridy = y++;
			pane.add(skillLevelCbx[i], c);
		}
		
		skillExpTxtField = new ValidateJTextField[noOfSkills];
		y = 1;
		for (int i = 0;i<noOfSkills;i++) {
			skillExpTxtField[i] = new ValidateJTextField ("Years Of Experience",ValidationRule.NUMERIC);
			c.ipady = 10;
			c.gridx = 2;
			c.gridy = y++;
			pane.add(skillExpTxtField[i], c);
		}
		
		return pane;
	}
	private void setInitData(){
		if(jobSeeker != null){
			nameTxtField.setText(jobSeeker.getName());
			userIdTxtField.setText(jobSeeker.getUserId());
			emailTxtField.setText(jobSeeker.getEmail());
			telNoTxtField.setText(jobSeeker.getTelNo());
			addressTxtField.setText(jobSeeker.getAddress());
		}
		
		if(jobAdvert != null){
			jobTitleTxtField.setText(jobAdvert.getTitle());
			positionTxtField.setText(jobAdvert.getPosition());
			jobDescriptionTxtField.setText(jobAdvert.getDescription());
			companyTxtField.setText(jobAdvert.getCompany().getName());
			locationCountryTxtField.setText(jobAdvert.getGeographicalLocation().getCountry());
			skillsList =  jobAdvert.getSkills();
			
			if(this.resumes != null && this.resumes.size() > 0){
				for(int i = 0 ; i<this.resumes.size(); i++){
					Resume  resume = resumes.get(i);
					String resumeName = resume.getResumeName();
					System.out.println("resume:" + resume);
					resumeName = (resumeName != null)?resumeName:"Resume " + (i+1);
					resumesCbx.addItem(resumeName);
					
				}
				
				//Show First Resume
				
				resumePreviewPanel = createResumePreviewPanel(resumes.get(0));
				resumePreviewScroller  = new JScrollPane(resumePreviewPanel); 
				resumePreviewScroller.setBounds(10, 280, 650, 200);
				resumePreviewScroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
				this.add(resumePreviewScroller);
				
				
				
			} else {
				resumesCbx.addItem("No Resume Found");
			}
			
			if(skillsList != null && skillsList.size() > 0){
				noOfSkills = skillsList.size();
				skillsPanel = createSkillsPanel();
				skillsPanel.setBounds(10, 660, 530, 150);
				this.add(skillsPanel);
			}
			
			
		}
	}
	@Override
	public void show() {
		// TODO Auto-generated method stub
		addFormPanel();
	}
	
	@SuppressWarnings("unused")
	private boolean skillValidate() throws ValidationException{
		
		
		responseSkillList = new ArrayList<Skill>();
		for (int i = 0;i<noOfSkills;i++) {
			
			Skill skill = skillsList.get(i);
			if(skill != null){
				    String tmpSkillName = skill.getSkillRef().getName();
					String tmpSkillRefId = skill.getSkillRef().getId();
					System.out.println("tmpSkillName:" + tmpSkillName);
					System.out.println("tmpSkillRefId:" + tmpSkillRefId);
					
					String tmpSkillLevel = skillLevelCbx[i].getSelectedItem().toString();
					System.out.println("tmpSkillLevel:" + tmpSkillLevel);
					
					if(tmpSkillLevel.equals("Select")){
						throw new ValidationException("Please Select Skill Level");
					}
					
					String tmpSkillExp =  skillExpTxtField[i].getValidatedText();
					if(tmpSkillExp.trim().length() == 0){
						throw new ValidationException("Please enter Years Of Experience");
					}
					
					Skill responseSkill = new Skill();
					responseSkill.setSkillRefId(tmpSkillRefId); 
					responseSkill.setLvl(Util.getSkillLevelCode(tmpSkillLevel));
					responseSkill.setYearOfExp(Integer.parseInt(tmpSkillExp));
					
					responseSkillList.add(responseSkill);
				
			}
		}
		return true;
		
	}
	
	public int displayConfirmationMsg() {
		return super.showConfirmDialog("Job", "Apply");
	}
	public void displayCompletionMsg() {
		showMsg("Apply Job successfully!", true);
	}	
	public void displayErrorMsg(String msg) {
		super.showMsg(msg,false);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource() == previewButton){
			int index = resumesCbx.getSelectedIndex();
	 	    if(resumes.get(index) != null ) {
	 	       	
				resumePreviewPanel = createResumePreviewPanel(resumes.get(index));
				resumePreviewScroller  = new JScrollPane(resumePreviewPanel); 
				resumePreviewScroller.setBounds(10, 280, 650, 200);
				resumePreviewScroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
				this.add(resumePreviewScroller);
	 	    }
		} else {
			super.clearMsg();
	        if(e.getActionCommand().equalsIgnoreCase(ActionBtnContants.APPLY_JOB)) {
				submit();
			}else if(e.getActionCommand().equalsIgnoreCase(ActionBtnContants.CANCEL)) {
				cancel();
			}
		}
	}
	
	 private void submit() {
		 
		
		 if(displayConfirmationMsg() == JOptionPane.YES_OPTION ) {
			 
			  try {
				  	 jobResponse = new JobResponse();
				  	 
				  	 if(skillValidate()){
						 jobResponse.setSkill(responseSkillList);
						
					 }
					 
				  	 jobResponse.setEmail(emailTxtField.getValidatedText());
				  	 jobResponse.setTelephoneNo(telNoTxtField.getValidatedText());
				  	 jobResponse.setAddress(addressTxtField.getValidatedText());
				  	 jobResponse.setJobAdvert(jobAdvert);
					 jobResponse.setJobSeeker(jobSeeker);
					 
					 if(this.resumes != null && this.resumes.size() > 0){
						 
						 int resumeIndex = resumesCbx.getSelectedIndex();
						 Resume resume = resumes.get(resumeIndex);
						 System.out.println("resume Name :" + resume);
						 if(resume!=null)
							 jobResponse.setResume(resume);
					 }
					 
					 
					 String expectedSalaryStr = expSalTxtField.getValidatedText();
					 String currentSalStr =  currentSalTxtField.getValidatedText();
					 if(expectedSalaryStr.trim().length() > 0)
						 expectedSalary = Float.parseFloat(expectedSalaryStr.trim());
					 if(currentSalStr.trim().length() > 0)
						 currentSalary = Float.parseFloat(currentSalStr.trim());
					 jobResponse.setExpectedSalary(expectedSalary);
					 jobResponse.setCurrentSalary(currentSalary);
					 
				     super.showMsg("Submission in Progress...",true);
			     
			         this.jobAdvertisementController.processApplyJob(jobResponse);
			         
			} catch (ValidationException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				super.showMsg(e.getMessage(),false);
			}
			catch (Exception e) {
				//e.printStackTrace();
				super.showMsg(e.getMessage(),false);
			}
		 }
	 }
	 
	 private void cancel() {
			reset();	
			super.showMsg("Action Cancelled",false);
		}
	 private void  reset(){
		 
	 }

}


